package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLArticleComment;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.fragments.RecommendFragment;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.adapter.ArticleCommentListAdapter;
import com.pocketsweet.utils.StringUtils;

@ContentView(R.layout.activity_article_comment)
public class ArticleComment extends BaseActivity implements OnClickListener,
		OnRefreshListener, OnLoadListener, OnItemClickListener {

	@ViewInject(R.id.imgBack)
	private ImageView imgBack;

	@ViewInject(R.id.edtComment)
	private EditText edtComment;

	@ViewInject(R.id.commentListview)
	private AutoListView commentListview;

	@ViewInject(R.id.linBlank)
	private LinearLayout linBlank;

	@ViewInject(R.id.tvSent)
	private TextView tvSent;

	@ViewInject(R.id.tvBlank)
	private TextView tvBlank;

	@ViewInject(R.id.tvBlankBg)
	private TextView tvBlankBg;

	private ArticleCommentListAdapter articleCommentListAdapter;
	private List<MLArticleComment> articleCommentList = new ArrayList<MLArticleComment>();
	public static final int MORE_DATA_MAX_COUNT = 10; // 每页10个对象
	public int skipDataCount = 0; // 忽略前N个对象
	private String articleID;
	private MLArticle mlArticle;
	private MLArticleComment mlArticleComment;
	private MLUser replyUser;
	private InputMethodManager manager;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Main.ACTION_COMMENT_COMMIT)) {
				articleCommentList.clear();
				articleCommentListAdapter.notifyDataSetChanged();
				getCommentList(AutoListView.REFRESH);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		articleCommentListAdapter = new ArticleCommentListAdapter(
				ArticleComment.this, articleCommentList);
		articleCommentListAdapter.notifyDataSetChanged();
		commentListview.setPageSize(MORE_DATA_MAX_COUNT);
		commentListview.setAdapter(articleCommentListAdapter);
		commentListview.setOnRefreshListener(this);
		commentListview.setOnLoadListener(this);
		commentListview.setOnItemClickListener(this);
		getCommentList(AutoListView.REFRESH);
		tvSent.setOnClickListener(this);
		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

	}

	/*
	 * 请求评论列表
	 */
	private void getCommentList(final int what) {
		mlArticle = RecommendFragment.mlArticle;
		if (mlArticle.getCommentCount() <= 0) {
			linBlank.setVisibility(View.VISIBLE);
			tvBlankBg.setBackgroundResource(R.drawable.blank_no_comment);
			tvBlank.setText(getResources().getString(R.string.blank_no_comment));
			commentListview.setNoData();
			return;
		}
		AVQuery<MLArticleComment> query = new AVQuery<MLArticleComment>(
				"MLArticleComment");
		skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
		if (what != AutoListView.LOAD) {
			skipDataCount = 0; // 刷新时不用忽略前面对象
		}
		query.whereEqualTo("article", mlArticle);
		query.setSkip(skipDataCount); // 忽略前N个
		query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
		query.orderByDescending("createdAt");
		query.include("user");
		query.include("reply_user");
		query.findInBackground(new FindCallback<MLArticleComment>() {
			@Override
			public void done(List<MLArticleComment> comment, AVException e) {
				// loading.dismiss();
				// 取出参与的人
				// Log.e("==user==", users.toString() + " ");
				if (e == null) {
					if (comment.size() > 0) {
						switch (what) {
						case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
							articleCommentList.clear();
							for (MLArticleComment mlComment : comment) {
								if (!StringUtils.isEmpty(mlComment.getContent())) {
									articleCommentList.add(mlComment);
								}
							}
							commentListview.onRefreshComplete();
							break;
						case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
							commentListview.onLoadComplete();
							for (MLArticleComment mlComment : comment) {
								if (!StringUtils.isEmpty(mlComment.getContent())) {
									articleCommentList.add(mlComment);
								}
							}
							break;
						}
						if (articleCommentList.size() > 0) {
							linBlank.setVisibility(View.GONE);
						} else {
							linBlank.setVisibility(View.VISIBLE);
							tvBlankBg
									.setBackgroundResource(R.drawable.blank_no_comment);
							tvBlank.setText(getResources().getString(
									R.string.blank_no_comment));

						}
						commentListview.setResultSize(articleCommentList.size());
						articleCommentListAdapter.setDatas(articleCommentList);
						articleCommentListAdapter.notifyDataSetChanged();
					} else {
						// 已加载完全部，取消loading
						linBlank.setVisibility(View.VISIBLE);
						commentListview.setNoData();
					}
				} else { // 出错
					commentListview.setNoData();
					linBlank.setVisibility(View.VISIBLE);
					tvBlankBg.setBackgroundResource(R.drawable.network_error);
					tvBlank.setText(getResources().getString(
							R.string.blank_network_error));
				}
			}
		});
	}

	/*
	 * 将评论保存该数据到leanCloud
	 */
	private void setMLArticleComment(String content, MLUser mlUser) {
		MLArticleComment mlArticleComment = new MLArticleComment();
		mlArticleComment.setObject(mlArticle);
		mlArticleComment.setContent(content);
		mlArticleComment.setType(0);
		mlArticleComment.setUser(mlUser);
		if (replyUser != null) {
			mlArticleComment.setReplyUser(replyUser);
		}
		mlArticleComment.saveInBackground(new SaveCallback() {

			@Override
			public void done(AVException arg0) {
				if (arg0 == null) {
					int commentCount = mlArticle.getCommentCount();

					// RecommendFragment.mlArticle.setCommentCount(++commentCount);
					// // 设置评论数加一
					RecommendFragment.isCommentRefresh = true;
					// RecommendFragment.mlArticle.saveInBackground();
					RecommendFragment.mlArticle.increment("commentCount");// 设置评论数加一

					RecommendFragment.mlArticle
							.saveInBackground(new SaveCallback() {

								@Override
								public void done(AVException arg0) {
									// TODO Auto-generated method stub

								}
							});
					edtComment.setText("");// 评论成功后提交评论，清空edittext并隐藏软键盘
					manager.hideSoftInputFromWindow(
							edtComment.getWindowToken(), 0);
					replyUser = null;
					edtComment.setHint("输入评论...");
					Intent intent = new Intent(); // 发送广播刷新评论列表
					intent.setAction(Main.ACTION_COMMENT_COMMIT);
					sendBroadcast(intent);
				} else {
				}
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(receiver);
	}

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Main.ACTION_COMMENT_COMMIT);
		this.registerReceiver(receiver, filter);

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void back(View v) {
		ArticleComment.this.finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tvSent:
			String editText = edtComment.getText().toString();
			if (!StringUtils.isEmpty(editText)) {
				setMLArticleComment(editText, UserService.getCurrentUser());
			}
			break;

		}
	}

	@Override
	public void onLoad() {
		getCommentList(AutoListView.LOAD);
	}

	@Override
	public void onRefresh() {
		getCommentList(AutoListView.REFRESH);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				replyUser = null;
				edtComment.setHint("输入评论...");
			}
		}
		return super.onTouchEvent(event);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		// TODO 点击回复用户的评论
		if (position - 1 < 0 || articleCommentList.size() <= 0 || position - 1 >= articleCommentList.size()) {
			return;
		}
		position = position - 1;
		mlArticleComment = articleCommentList.get(position);
		replyUser = mlArticleComment.getUser();
		if (replyUser == null)
			return;
		edtComment.setHint("回复" + replyUser.getNickname().toString() + ":");
		// InputMethodManager manager = (InputMethodManager)
		// getSystemService(Context.INPUT_METHOD_SERVICE);
		// if (manager.isActive()) { // 当软件盘弹出时，点击评论listview即收回软件盘，且不回复任何人
		// Log.e("==", "==open");
		// manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
		// InputMethodManager.HIDE_NOT_ALWAYS);
		// replyUser = null;
		// edtComment.setHint("输入评论...");
		// } else {
		// Log.e("==", "==close");
		// }
		// }
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}
}
